package com.supermap.desktop;

import java.awt.Component;
import java.awt.Point;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.awt.Cursor;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import com.supermap.data.CoordSysTransMethod;
import com.supermap.data.CoordSysTransParameter;
import com.supermap.data.CoordSysTranslator;
import com.supermap.data.Dataset;
import com.supermap.data.DatasetType;
import com.supermap.data.DatasetVector;
import com.supermap.data.GeoStyle;
import com.supermap.data.GeoText;
import com.supermap.data.Geometry;
import com.supermap.data.Point2D;
import com.supermap.data.Point2Ds;
import com.supermap.data.PrjCoordSys;
import com.supermap.data.Recordset;
import com.supermap.data.Rectangle2D;
import com.supermap.data.Resources;
import com.supermap.data.SymbolType;
import com.supermap.data.Workspace;
import com.supermap.desktop.Interface.IContextMenuManager;
import com.supermap.desktop.Interface.IFormMap;
import com.supermap.desktop.dialog.DialogSaveAsMap;
import com.supermap.desktop.enums.WindowType;
import com.supermap.desktop.event.ActiveLayersChangedEvent;
import com.supermap.desktop.event.ActiveLayersChangedListener;
import com.supermap.desktop.exception.InvalidScaleException;
import com.supermap.desktop.implement.SmComboBox;
import com.supermap.desktop.implement.SmLabel;
import com.supermap.desktop.implement.SmTextField;
import com.supermap.desktop.mapview.MapViewProperties;
import com.supermap.desktop.properties.CommonProperties;
import com.supermap.desktop.ui.FormBaseChild;
import com.supermap.desktop.ui.UICommonToolkit;
import com.supermap.desktop.ui.LayersComponentManager;
import com.supermap.desktop.ui.controls.DialogResult;
import com.supermap.desktop.ui.controls.LayersTree;
import com.supermap.desktop.ui.controls.NodeDataType;
import com.supermap.desktop.ui.controls.SymbolDialog;
import com.supermap.desktop.ui.controls.TreeNodeData;
import com.supermap.mapping.Layer;
import com.supermap.mapping.LayerGroup;
import com.supermap.mapping.LayerSettingVector;
import com.supermap.mapping.Map;
import com.supermap.mapping.MapDrawingEvent;
import com.supermap.mapping.MapDrawingListener;
import com.supermap.mapping.Selection;
import com.supermap.ui.Action;
import com.supermap.ui.GeometrySelectedEvent;
import com.supermap.ui.GeometrySelectedListener;
import com.supermap.ui.MapControl;
import com.supermap.ui.TrackMode;

public class FormMap extends FormBaseChild implements IFormMap {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final double MAX_SCALE_VALUE = 1E10;
	private static final double MIN_SCALE_VALUE = 1E-10;

	private MapControl mapControl = null;
	JScrollPane jScrollPaneChildWindow = null;
	private LayersTree layersTree = null;
	private EventListenerList listenerList = new EventListenerList();
	private ArrayList<Layer> activeLayersList = new ArrayList<Layer>();
	private boolean isMouseClickLeft;
	private SmComboBox scaleBox;

	private MouseAdapter layersTreeMouseAdapter = new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
			layersTree_MouseClicked(e);
		}
	};
	private int SELECT_NUMBER = 1;
	private int LOCATION = 2;
	private int PRJCOORSYS = 3;
	private int CENTER_X = 5;
	private int CENTER_Y = 6;
	private int SCALE = 8;

	// 地图窗口右键菜单
	private JPopupMenu formMapContextMenu;

	public JPopupMenu getFormMapContextMenu() {
		return this.formMapContextMenu;
	}

	// 几何对象右键菜单
	private JPopupMenu geometryContextMenu;

	public JPopupMenu getGeometryContextMenu() {
		return this.geometryContextMenu;
	}

	// 文本对象右键菜单
	private JPopupMenu geometryTextContextMenu;

	public JPopupMenu getGeometryTextContextMenu() {
		return this.geometryTextContextMenu;
	}

	// 参数化几何对象右键菜单
	private JPopupMenu geometryParmaContextMenu;

	public JPopupMenu getGeometryParmaContextMenu() {
		return this.geometryParmaContextMenu;
	}

	private LayersTreeSelectionListener layersTreeSelectionListener = new LayersTreeSelectionListener();
	private MouseListener mapControl_MouseListener = new MouseAdapter() {

		@Override
		public void mouseClicked(MouseEvent e) {
			int buttonType = e.getButton();
			int clickCount = e.getClickCount();

			if (buttonType == MouseEvent.BUTTON3
					&& clickCount == 1
					&& (getMapControl().getAction() == Action.SELECT || getMapControl().getAction() == Action.SELECT2 || getMapControl().getAction() == Action.SELECTCIRCLE)
					&& getMapControl().getTrackMode() == TrackMode.EDIT) {
				showPopupMenu(e);
			}

			if (getMapControl().getAction() == Action.SELECTLINE || getMapControl().getAction() == Action.SELECTREGION
					|| getMapControl().getAction() == Action.SELECTRECTANGLE) {
				if (buttonType == MouseEvent.BUTTON1) {
					isMouseClickLeft = true;
				} else if (buttonType == MouseEvent.BUTTON3) {
					if (!isMouseClickLeft) {
						showPopupMenu(e);
					}
					isMouseClickLeft = false;
				} else {
					isMouseClickLeft = false;
				}
			}
		}
	};

	public FormMap() {
		this("");
	}

	public FormMap(String name) {
		this(name, null, null);
	}

	public FormMap(String title, Icon icon, Component component) {
		super(title, icon, component);

		this.mapControl = new MapControl();
		this.mapControl.getMap().setWorkspace(Application.getActiveApplication().getWorkspace());
		this.mapControl.getMap().setName(title);
		this.mapControl.addMouseListener(mapControl_MouseListener);
		jScrollPaneChildWindow = new JScrollPane(mapControl);
		this.setComponent(jScrollPaneChildWindow);

		this.layersTree = UICommonToolkit.getLayersManager().getLayersTree();
		scaleBox = (SmComboBox) getStatusbar().getComponent(SCALE);
		if (Application.getActiveApplication().getMainFrame() != null) {
			IContextMenuManager manager = Application.getActiveApplication().getMainFrame().getContextMenuManager();

			this.formMapContextMenu = (JPopupMenu) manager.get("SuperMap.Desktop._FormMap.FormMapContextMenu");
			this.geometryContextMenu = (JPopupMenu) manager.get("SuperMap.Desktop._FormMap.GeometryContextMenu");
			this.geometryTextContextMenu = (JPopupMenu) manager.get("SuperMap.Desktop._FormMap.GeometryTextContextMenu");
			this.geometryParmaContextMenu = (JPopupMenu) manager.get("SuperMap.Desktop._FormMap.GeometryParmaContextMenu");
		}

		((SmLabel) getStatusbar().getComponent(SELECT_NUMBER)).setText("0");
		((SmTextField) getStatusbar().getComponent(LOCATION)).setSize(300, 20);

		final SmTextField pointXField = (SmTextField) getStatusbar().getComponent(CENTER_X);
		final SmTextField pointYField = (SmTextField) getStatusbar().getComponent(CENTER_Y);

		// 重置中心点
		pointXField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				resetCenter(e, pointXField, pointYField);
			}
		});
		pointYField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				resetCenter(e, pointXField, pointYField);
			}
		});
		// 中心点数据格式化
		final DecimalFormat format = new DecimalFormat("######0.0000");
		// 初始化中心点
		initCenter(format, pointXField, pointYField);
		this.mapControl.getMap().addDrawingListener(new MapDrawingListener() {

			@Override
			public void mapDrawing(MapDrawingEvent arg0) {
				initCenter(format, pointXField, pointYField);
				// 初始化比例尺下拉框
				initScaleComboBox();
				((SmTextField) getStatusbar().getComponent(PRJCOORSYS)).setText(mapControl.getMap().getPrjCoordSys().getName());
			}
		});

		// 比例尺下拉框添加选择事件
		scaleBox.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				scaleBox_ItemChange(e);
			}
		});
		// 抓取选择个数
		mapControl.addGeometrySelectedListener(new GeometrySelectedListener() {

			@Override
			public void geometrySelected(GeometrySelectedEvent arg0) {
				((SmLabel) getStatusbar().getComponent(SELECT_NUMBER)).setText(String.valueOf(arg0.getCount()));
			}
		});

		mapControl.addMouseMotionListener(new MouseMotionListener() {

			@Override
			public void mouseMoved(MouseEvent e) {
				mapControl_mouseMove(e);
			}

			@Override
			public void mouseDragged(MouseEvent e) {
				initCenter(format, pointXField, pointYField);
			}
		});
		this.mapControl.addMouseWheelListener(new MouseWheelListener() {

			@Override
			public void mouseWheelMoved(MouseWheelEvent e) {
				initCenter(format, pointXField, pointYField);
				initScaleComboBox();
			}
		});
		// 拖拽处理
		initDrag();
	}

	protected void resetCenter(KeyEvent e, SmTextField pointXField, SmTextField pointYField) {
		try {
			if (e.getKeyChar() == KeyEvent.VK_ENTER) {
				double pointX = Double.parseDouble(pointXField.getText());
				double pointY = Double.parseDouble(pointYField.getText());
				Point2D point2d = new Point2D(pointX, pointY);
				mapControl.getMap().setCenter(point2d);
				mapControl.getMap().refresh();
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	/**
	 * 监听地图控件鼠标移动事件，获得鼠标所在位置对应的经纬度
	 * 
	 * @param e
	 */
	protected void mapControl_mouseMove(MouseEvent e) {
		try {
			Point pointMouse = new Point(e.getX(), e.getY());
			Point2D point = mapControl.getMap().pixelToMap(pointMouse);
			if (-180.0 <= point.getX() && point.getX() <= 180.0 && -90.0 <= point.getY() && point.getY() <= 90.0) {
				((SmTextField) getStatusbar().getComponent(LOCATION)).setText(CommonProperties.getString("String_PrjCoordSys_LongitudeLatitude")
						.replace("{0:F6}", String.valueOf(point.getX())).replace("{1:F6}", String.valueOf(point.getY())));
			} else {
				((SmTextField) getStatusbar().getComponent(LOCATION)).setText("X:" + point.getX() + "," + "Y:" + point.getY());
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	/**
	 * 
	 * @param e
	 */
	protected void scaleBox_ItemChange(ItemEvent e) {
		String scaleString = (String) scaleBox.getSelectedItem();
		int selectIndex = scaleBox.getSelectedIndex();
		try {
			if (-1 != selectIndex && !"0.0".equals(scaleString)) {
				ScaleModel model = new ScaleModel(scaleString);
				double value = model.getScale();
				if (Double.compare(value, mapControl.getMap().getScale()) != 0 && value < MAX_SCALE_VALUE && value > MIN_SCALE_VALUE) {
					mapControl.getMap().setScale(model.getScale());
					mapControl.getMap().refresh();
				}
			}
		} catch (InvalidScaleException ex) {
			// TODO 不合法的比例尺设置，后续按需求增加日志记录功能
			Application.getActiveApplication().getOutput().output(ex);
		} catch (Exception e2) {
			Application.getActiveApplication().getOutput().output(e2);
		}
	}

	/**
	 * 初始化比例尺下拉菜单
	 */
	@SuppressWarnings("unchecked")
	private void initScaleComboBox() {
		try {
			scaleBox.removeAllItems();
			String scale = new ScaleModel(mapControl.getMap().getScale()).toString();
			if ("NONE".equals(scale)) {
				scale = String.valueOf(mapControl.getMap().getScale());
			}

			scaleBox.addItem(scale);
			scaleBox.addItem(ScaleModel.SCALE_5000);
			scaleBox.addItem(ScaleModel.SCALE_10000);
			scaleBox.addItem(ScaleModel.SCALE_25000);
			scaleBox.addItem(ScaleModel.SCALE_50000);
			scaleBox.addItem(ScaleModel.SCALE_100000);
			scaleBox.addItem(ScaleModel.SCALE_250000);
			scaleBox.addItem(ScaleModel.SCALE_500000);
			scaleBox.addItem(ScaleModel.SCALE_1000000);
		} catch (Exception e) {
			Application.getActiveApplication().getOutput().output(e);
		}

	}

	private void initCenter(DecimalFormat format, SmTextField pointX, SmTextField pointY) {
		pointX.setText(format.format(mapControl.getMap().getCenter().getX()));
		pointY.setText(format.format(mapControl.getMap().getCenter().getY()));
	}

	@Override
	public MapControl getMapControl() {
		return this.mapControl;
	}

	@Override
	public Layer[] getActiveLayers() {
		Layer[] layers = new Layer[this.activeLayersList.size()];
		this.activeLayersList.toArray(layers);
		return layers;
	}

	@Override
	public void setActiveLayers(Layer[] activeLayers) {
		Layer[] oldLayers = getActiveLayers();

		if (activeLayers != null && activeLayers.length > 0) {
			this.activeLayersList.clear();
			ArrayList<TreePath> paths = new ArrayList<TreePath>();

			for (Layer layer : activeLayers) {
				if (this.mapControl.getMap().getLayers().contains(layer.getName())) {
					this.activeLayersList.add(layer);

					DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.layersTree.getModel().getRoot();
					for (int i = 0; i < root.getChildCount(); i++) {
						DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
						TreeNodeData nodeData = (TreeNodeData) node.getUserObject();

						if (isNodeLayer(nodeData.getType()) && nodeData.getData() == layer) {
							paths.add(new TreePath(node.getPath()));
							break;
						}
					}
				}
			}

			this.layersTree.setSelectionPaths(paths.toArray(new TreePath[paths.size()]));
		} else {
			this.layersTree.clearSelection();
			this.activeLayersList.clear();
		}

		if (oldLayers != null && oldLayers.length > 0 && !this.activeLayersList.isEmpty()) {
			fireActiveLayersChanged(new ActiveLayersChangedEvent(this, oldLayers, getActiveLayers()));
		}
	}

	@Override
	public String getText() {
		return super.getTitle();
	}

	@Override
	public void setText(String text) {
		super.setTitle(text);
	}

	@Override
	public WindowType getWindowType() {
		return WindowType.MAP;
	}

	@Override
	public boolean save() {
		boolean result = false;
		try {
			if (this.isNeedSave()) {
				Workspace workspace = Application.getActiveApplication().getWorkspace();
				if (workspace != null) {
					if (workspace.getMaps().indexOf(this.getText()) >= 0) {
						// CancelEventArgs e = new CancelEventArgs();
						// RaiseSavingEvent(e);
						// if (!e.Cancel) {
						result = workspace.getMaps().setMapXML(this.getText(), this.mapControl.getMap().toXML());
						// RaiseSavedEvent();
						// }
					} else {
						result = save(true, true);
					}
				}
				if (result) {
					this.mapControl.getMap().setModified(false);
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	@Override
	public boolean save(boolean notify, boolean isNewWindow) {
		boolean result = false;
		try {
			if (this.isNeedSave()) {
				Workspace workspace = Application.getActiveApplication().getWorkspace();
				if (workspace != null) {
					if (notify) {
						result = this.saveAs(isNewWindow);
					} else {
						// CancelEventArgs e = new CancelEventArgs();
						// RaiseSavingEvent(e);
						//
						// if (!e.Cancel) {
						result = workspace.getMaps().add(this.getText(), this.mapControl.getMap().toXML()) >= 0;
						// RaiseSavedEvent();
						// }
					}
				}

				if (result) {
					this.mapControl.getMap().setModified(false);
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	@Override
	public boolean saveAs(boolean isNewWindow) {
		boolean result = false;
		try {
			Workspace workspace = Application.getActiveApplication().getWorkspace();
			DialogSaveAsMap dialogSaveAs = new DialogSaveAsMap();
			dialogSaveAs.setMaps(workspace.getMaps());
			dialogSaveAs.setMapName(this.getText());
			dialogSaveAs.setIsNewWindow(isNewWindow);
			if (dialogSaveAs.showDialog() == DialogResult.YES) {
				// CancelEventArgs e = new CancelEventArgs();
				// RaiseSavingEvent(e);
				// if (!e.Cancel) {
				this.mapControl.getMap().setName(dialogSaveAs.getMapName());
				result = workspace.getMaps().add(dialogSaveAs.getMapName(), this.mapControl.getMap().toXML()) >= 0;
				if (result) {
					this.setText(dialogSaveAs.getMapName());
					// }
					// RaiseSavedEvent();
				}
			} else {
				result = false;
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	@Override
	public boolean isNeedSave() {
		return this.mapControl.getMap().isModified();
	}

	@Override
	public void setNeedSave(boolean needSave) {
		this.mapControl.getMap().setModified(needSave);
	}

	@Override
	public boolean saveFormInfos() {
		// TODO Auto-generated method stub
		return false;
	}

	public final void addActiveLayersChangedListener(ActiveLayersChangedListener listener) {
		listenerList.add(ActiveLayersChangedListener.class, listener);
	}

	public final void removeActiveLayersChangedListener(ActiveLayersChangedListener listener) {
		listenerList.remove(ActiveLayersChangedListener.class, listener);
	}

	protected void fireActiveLayersChanged(ActiveLayersChangedEvent e) {
		Object[] listeners = listenerList.getListenerList();

		for (int i = listeners.length - 2; i >= 0; i -= 2) {
			if (listeners[i] == ActiveLayersChangedListener.class) {
				((ActiveLayersChangedListener) listeners[i + 1]).acitiveLayersChanged(e);
			}
		}
	}

	private void LayersTreeSelectionChanged() {
		TreePath[] selectedPaths = this.layersTree.getSelectionPaths();
		Layer[] oldActiveLayers = getActiveLayers();

		this.activeLayersList.clear();
		if (selectedPaths != null) {
			for (TreePath path : selectedPaths) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

				if (node != null) {
					TreeNodeData nodeData = (TreeNodeData) node.getUserObject();

					if (isNodeLayer(nodeData.getType()) && nodeData.getData() instanceof Layer) {
						this.activeLayersList.add((Layer) nodeData.getData());
					}
				}
			}
		}

		if (oldActiveLayers != null && oldActiveLayers.length > 0 && !this.activeLayersList.isEmpty()) {
			fireActiveLayersChanged(new ActiveLayersChangedEvent(this, oldActiveLayers, getActiveLayers()));
		}
	}

	private boolean isNodeLayer(NodeDataType nodeDataType) {
		return nodeDataType == NodeDataType.LAYER || nodeDataType == NodeDataType.LAYER_IMAGE || nodeDataType == NodeDataType.LAYER_THEME
				|| nodeDataType == NodeDataType.LAYER_GRID || nodeDataType == NodeDataType.THEME_UNIQUE || nodeDataType == NodeDataType.THEME_RANGE
				|| nodeDataType == NodeDataType.THEME_LABEL_ITEM || nodeDataType == NodeDataType.THEME_UNIQUE_ITEM
				|| nodeDataType == NodeDataType.THEME_RANGE_ITEM;
	}

	private void showPopupMenu(MouseEvent e) {
		Recordset recordset = null;
		try {
			boolean selected = false;
			Selection selection = null;
			ArrayList<Layer> layers = CommonToolkit.MapWrap.getLayers(this.getMapControl().getMap());
			for (Layer layer : layers) {
				selection = layer.getSelection();
				if (selection != null && selection.getCount() > 0) {
					selected = true;
					break;
				}
			}

			if (selected) {
				recordset = selection.toRecordset();
				recordset.moveFirst();
				Geometry geo = recordset.getGeometry();
				if (geo != null && geo instanceof GeoText) {
					this.getGeometryTextContextMenu().show((Component) this.getMapControl(), (int) e.getPoint().getX(), (int) e.getPoint().getY());
				} else {
					this.getGeometryContextMenu().show((Component) this.getMapControl(), (int) e.getPoint().getX(), (int) e.getPoint().getY());
				}
				if (geo != null) {
					geo.dispose();
				}
			} else {
				this.getFormMapContextMenu().show((Component) this.getMapControl(), (int) e.getPoint().getX(), (int) e.getPoint().getY());
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		if (recordset != null) {
			recordset.dispose();
		}
	}

	@Override
	public void actived() {
		try {
			LayersComponentManager layersComponentManager = UICommonToolkit.getLayersManager();
			if (layersComponentManager != null) {
				boolean exist = false;
				for (int i = 0; i < Application.getActiveApplication().getMainFrame().getFormManager().getCount(); i++) {
					if (Application.getActiveApplication().getMainFrame().getFormManager().get(i) instanceof FormMap) {
						FormMap formMap = (FormMap) Application.getActiveApplication().getMainFrame().getFormManager().get(i);
						if (formMap != null && formMap.getText() == this.getText()) {
							exist = true;
							break;
						}
					}
				}

				if (exist) {
					layersComponentManager.setMap(this.getMapControl().getMap());
					this.layersTree.addTreeSelectionListener(this.layersTreeSelectionListener);
					this.layersTree.addMouseListener(this.layersTreeMouseAdapter);
					setActiveLayers(getActiveLayers());
				} else {
					layersComponentManager.setMap(null);
				}

				if (exist) {
					this.getMapControl().getMap().refresh();
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	@Override
	public void deactived() {
		try {
			this.layersTree.removeTreeSelectionListener(this.layersTreeSelectionListener);
			this.layersTree.removeMouseListener(this.layersTreeMouseAdapter);
			if (this.layersTree != null) {
				this.layersTree.setMap(null);
				// if (layersTree != null) {
				// layersTree.SelectionChanged -= new
				// SelectionChangedEventHandler(m_layersTree_SelectionChanged);
				// }
			}
			//
			// IDockBar dockBarTheme =
			// SuperMap.Desktop.Application.ActiveApplication.MainForm.DockBarManager[typeof(_ControlThemePropertyDockBar)];
			// if (dockBarTheme != null && dockBarTheme.Visible)
			// {
			// _ControlThemePropertyDockBar themeDockBarContainer =
			// dockBarTheme.Control as _ControlThemePropertyDockBar;
			// _ThemePropertyContainer themePropertyContainer =
			// themeDockBarContainer.UserControl as _ThemePropertyContainer;
			// if (themePropertyContainer != null)
			// {
			// themePropertyContainer.RemoveAllControls();
			// }
			// }
			//
			// if (m_dropDownFormLegend != null)
			// {
			// m_dropDownFormLegend.Close();
			// m_dropDownFormLegend = null;
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	/**
	 * 窗体被激活时候触发
	 */
	@Override
	public void windowShown() {

	}

	/**
	 * 窗体被隐藏时候触发
	 */
	@Override
	public void windowHidden() {

	}

	public void layersTree_MouseClicked(MouseEvent e) {
		try {
			if (e.getButton() == 1 && e.getClickCount() == 2) {
				TreePath path = this.layersTree.getPathForLocation(e.getX(), e.getY());
				if (path != null) {
					Object object = path.getLastPathComponent();
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) object;
					TreeNodeData data = (TreeNodeData) node.getUserObject();
					NodeDataType type = data.getType();
					if (type.equals(NodeDataType.LAYER)) {
						Layer layer = (Layer) data.getData();
						if (layer.getTheme() == null) {
							// 设置图层属性
							this.showStyleSetDialog();
						} else {
							// 修改专题图风格
						}
					}
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	/**
	 * 弹出风格设置窗口，返回选中的新风格
	 */
	public void showStyleSetDialog() {
		try {
			SymbolType symbolType = SymbolType.MARKER;
			LayersComponentManager layersComponentManager = UICommonToolkit.getLayersManager();
			TreePath[] selections = this.layersTree.getSelectionPaths();

			Layer layer = null;
			for (int index = 0; index < selections.length; index++) {
				DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) selections[index].getLastPathComponent();
				TreeNodeData treeNodeData = (TreeNodeData) treeNode.getUserObject();
				Layer tempLayer = (Layer) treeNodeData.getData();
				if (tempLayer != null && tempLayer.getTheme() == null && tempLayer.getDataset() != null) {
					if (CommonToolkit.DatasetTypeWrap.isPoint(tempLayer.getDataset().getType())) {
						symbolType = SymbolType.MARKER;
						layer = tempLayer;
						break;
					} else if (CommonToolkit.DatasetTypeWrap.isLine(tempLayer.getDataset().getType())) {
						symbolType = SymbolType.LINE;
						layer = tempLayer;
						break;
					} else if (CommonToolkit.DatasetTypeWrap.isRegion(tempLayer.getDataset().getType())) {
						symbolType = SymbolType.FILL;
						layer = tempLayer;
						break;
					}
				}
			}

			// notify by huchenpu 2015-06-30
			// 多选需要让用户指定设置哪些风格，现在暂时先只处理第一个图层
			if (layer != null && selections.length > 1) {
				GeoStyle layerStyle = ((LayerSettingVector) layer.getAdditionalSetting()).getStyle();
				GeoStyle geostyle = changeGeoStyle(layerStyle, symbolType);
				if (geostyle != null) {
					LayerSettingVector layerSetting = (LayerSettingVector) layer.getAdditionalSetting();
					layerSetting.setStyle(geostyle);
					this.getMapControl().getMap().refresh();
				}
			} else if (layer != null && selections.length == 1) {
				GeoStyle layerStyle = ((LayerSettingVector) layer.getAdditionalSetting()).getStyle();
				GeoStyle geostyle = changeGeoStyle(layerStyle, symbolType);
				if (geostyle != null) {
					LayerSettingVector layerSetting = (LayerSettingVector) layer.getAdditionalSetting();
					layerSetting.setStyle(geostyle);
					// layerNode.Image = null;
					this.getMapControl().getMap().refresh();
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	public void removeLayers(Layer[] layers) {
		try {
			if (layers != null && layers.length > 0) {
				ArrayList<String> removingLayers = new ArrayList<String>();
				String message = "";
				if (layers.length == 1) {
					message = String.format(MapViewProperties.getString("String_validateRemoveLayerMessage"), layers[0].getCaption());
				} else {
					message = String.format(MapViewProperties.getString("String_validateRemoveRangeMessage"), layers.length);
				}

				int result = UICommonToolkit.showConfirmDialog(message);
				if (result == JOptionPane.OK_OPTION) {
					for (Layer layer : layers) {
						if (layer instanceof LayerGroup) {
							ArrayList<Layer> childLayers = CommonToolkit.MapWrap.getLayers((LayerGroup) layer);
							for (Layer childLayer : childLayers) {
								Dataset dataset = childLayer.getDataset();
								if (dataset == null) {
									if (childLayer.getBounds().getWidth() > 0 || childLayer.getBounds().getHeight() > 0) {
										break;
									}
								} else {
									// 有可能存在一个点的数据集，所以还是用记录集来判断吧
									if (dataset instanceof DatasetVector && ((DatasetVector) dataset).getRecordCount() > 0) {
										break;
									}
								}
							}
						} else {
							Dataset dataset = layer.getDataset();
							if (dataset == null) {
								if (layer.getBounds().getWidth() > 0 || layer.getBounds().getHeight() > 0) {
									break;
								}
							} else {
								// 有可能存在一个点的数据集，所以还是用记录集来判断吧
								if (dataset instanceof DatasetVector && ((DatasetVector) dataset).getRecordCount() > 0) {
								}
							}
						}

						removingLayers.add(layer.getName());
					}

					for (int i = 0; i < removingLayers.size(); i++) {
						CommonToolkit.MapWrap.reomveLayer(this.getMapControl().getMap(), removingLayers.get(i));
					}

					this.getMapControl().getMap().refresh();
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	public void geometryViewEntire() {
		try {
			Recordset recordset = null;
			Rectangle2D rect = Rectangle2D.getEMPTY();
			ArrayList<Layer> layers = CommonToolkit.MapWrap.getLayers(this.getMapControl().getMap());
			for (Layer layer : layers) {
				if (layer.getSelection() != null && layer.getSelection().getCount() > 0) {
					recordset = layer.getSelection().toRecordset();
					if (recordset != null) {
						Rectangle2D layerSelectionBounds = recordset.getBounds();
						if (this.getMapControl().getMap().isDynamicProjection()) {
							PrjCoordSys recordCoordSys = recordset.getDataset().getPrjCoordSys();
							PrjCoordSys mapCoordSys = this.getMapControl().getMap().getPrjCoordSys();
							if (recordCoordSys.getType() != mapCoordSys.getType()) {
								Point2Ds points = new Point2Ds(new Point2D[] { new Point2D(layerSelectionBounds.getLeft(), layerSelectionBounds.getBottom()),
										new Point2D(layerSelectionBounds.getRight(), layerSelectionBounds.getTop()) });
								CoordSysTransParameter transParameter = new CoordSysTransParameter();
								try {
									CoordSysTranslator.convert(points, recordCoordSys, mapCoordSys, transParameter, CoordSysTransMethod.MTH_COORDINATE_FRAME);
									layerSelectionBounds = new Rectangle2D(points.getItem(0), points.getItem(1));
								} finally {
									transParameter.dispose();
								}
							}
						}

						// 直接用记录集的Bounds modified by zengwh 2012-1-6
						if (rect.isEmpty()) {
							rect = layerSelectionBounds;
						} else {
							rect.union(layerSelectionBounds);
						}
						recordset.dispose();
						recordset = null;
					}
				}
			}

			if (!rect.isEmpty()) {
				this.getMapControl().getMap().setViewBounds(rect);
				this.getMapControl().getMap().refresh();
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	private GeoStyle changeGeoStyle(GeoStyle beforeStyle, SymbolType symbolType) {
		GeoStyle result = null;
		SymbolDialog symbolDialog = null;
		try {
			Resources resources = Application.getActiveApplication().getWorkspace().getResources();

			((JFrame) Application.getActiveApplication().getMainFrame()).setCursor(Cursor.WAIT_CURSOR);
			symbolDialog = new SymbolDialog();
			DialogResult dialogResult = symbolDialog.showDialog(resources, beforeStyle, symbolType);
			if (dialogResult == DialogResult.OK) {
				result = symbolDialog.getStyle();
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		} finally {
			((JFrame) Application.getActiveApplication().getMainFrame()).setCursor(Cursor.DEFAULT_CURSOR);
		}
		return result;
	}

	private class LayersTreeSelectionListener implements TreeSelectionListener {

		@Override
		public void valueChanged(TreeSelectionEvent e) {
			LayersTreeSelectionChanged();
		}
	}

	/**
	 * 拖动实现将数据集添加到当前地图图层
	 */
	private void initDrag() {
		new DropTarget(this, new WorkspaceTreeDropTargetAdapter());
	}

	/**
	 * 用于提供所涉及的 DropTarget 的 DnD 操作的通知
	 * 
	 * @author xie
	 */
	private class WorkspaceTreeDropTargetAdapter extends DropTargetAdapter {

		@Override
		public void drop(DropTargetDropEvent dtde) {
			try {
				// 将数据集添加到当前地图图层
				Dataset[] datasets = Application.getActiveApplication().getActiveDatasets();
				IFormMap formMap = (IFormMap) Application.getActiveApplication().getActiveForm();
				Map map = formMap.getMapControl().getMap();
				for (Dataset dataset : datasets) {
					if (dataset.getType() != DatasetType.TABULAR && dataset.getType() != DatasetType.TOPOLOGY) {
						map.getLayers().add(dataset, true);
					}
				}

				map.refresh();
				UICommonToolkit.getLayersManager().setMap(map);
			} catch (Exception e) {
				Application.getActiveApplication().getOutput().output(e);
			}

		}

	}

}
